package com.sbio.udiapp.net.exception;

import android.net.ParseException;

import com.fasterxml.jackson.core.JsonParseException;

import org.json.JSONException;

import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketException;
import java.net.UnknownHostException;

import retrofit2.HttpException;

public class ApiException extends Exception {
    public static int error_unknown = 1000;
    public static int error_parse = 1001;
    public static int error_network_request = 1002;
    public static int error_timeout = 1003;

    private int code;

    private String errMsg;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getErrMsg() {
        return errMsg;
    }

    public void setErrMsg(String errMsg) {
        this.errMsg = errMsg;
    }

    public ApiException(int code, String errMsg) {
        this.code = code;
        this.errMsg = errMsg;
    }

    public ApiException() {
    }

    public static ApiException handleException(Throwable throwable) {
        ApiException ex;
        if (throwable instanceof JsonParseException
                || throwable instanceof JSONException
                || throwable instanceof ParseException
        ) {
            ex = new ApiException(error_parse, "数据解析异常" + throwable.getMessage());
        } else if (throwable instanceof ConnectException
                || throwable instanceof UnknownHostException
                || throwable instanceof SocketException
                || throwable instanceof HttpException
                || throwable instanceof retrofit2.adapter.rxjava2.HttpException
                || (throwable instanceof IOException && throwable.getMessage().contains("unexpected end of stream on"))
        ) {
            ex = new ApiException(error_network_request, "网络请求异常" + throwable.getMessage());
        } else if (throwable instanceof java.net.SocketTimeoutException) {
            ex = new ApiException(error_network_request, "网络请求超时");
        } else {
            ex = new ApiException(error_unknown, "未知异常:\n" + throwable.getMessage());
        }
        return ex;
    }
}
